#ifndef ECMASCRIPT_H
#define ECMASCRIPT_H
#include <QString>
#include <QJSEngine>
#include <QJSValue>
//#include <QScriptEngine>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QDate>

namespace JS
{
class myObject:public QObject
{
    Q_OBJECT
public:
    int Fact;
    myObject():Fact(7){};
    ~myObject(){}
public slots:
    int add(int a,int b){return a*100+b*10+Fact;}
public:
    int addx(int a,int b){return a*1000+b*100+Fact;}
};

    static void Run()
    {
        QQmlApplicationEngine engine;
        QJSEngine jsEngine;
        //自定义JS函数
        QJSValue fun = jsEngine.evaluate("(function(a,b){return a*100+b;})");
        QJSValueList args;
        args<<8<<9;
        args.append(80);
        args.append(90);
        //调用带参数的JS函数
        QJSValue v1 = fun.call(args);
        qDebug()<<v1.toString()<<QDate::currentDate();

        //执行JS函数
        QJSValue v2 = jsEngine.evaluate("(function() { return 'Hello, World!'; })()");
        qDebug()<<v2.toString()<<QDate::currentDate();

        //设置全局变量
        jsEngine.globalObject().setProperty("mx",9527);
        //使用全局变量
        QJSValue v3 = jsEngine.evaluate("mx=mx+100;mx;");
        qDebug()<<v3.toString()<<QDate::currentDate();
        v3 = jsEngine.evaluate("mx=mx+100;mx;");
        qDebug()<<v3.toString()<<QDate::currentDate();

        //导入JS模块
        QJSValue module = jsEngine.importModule("./m.js");
        QJSValue m0 = module.property("addx");
        QJSValue v4 = m0.call(args);
        qDebug()<<v4.toString()<<QDate::currentDate();


        //为脚本提供C++类
        //1.派生子QObject,通过 QJSEngine::NewQObject()
        //2.为类编写C++原型和构造函数，脚本中使用new
        myObject mobj;
        QJSValue jobj = jsEngine.newQObject(&mobj); //方式1
        jsEngine.globalObject().setProperty("jobj",jobj);
        QJSValue v5 = jsEngine.evaluate("jobj.add(9,8)");
        qDebug()<<v5.toString()<<QDate::currentDate();
        QJSValue v6 = jsEngine.evaluate("jobj.addx(9,8)"); //只能使用槽函数
        qDebug()<<v6.toString()<<QDate::currentDate();
        QJSValue jobj2 = jsEngine.newQMetaObject(mobj.metaObject()); //建议用于静态元对象
        jsEngine.globalObject().setProperty("G",jobj2);

    }
}


#endif // ECMASCRIPT_H
